package com.szgz.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szgz.platform.mapper.TaskMapper;
import com.szgz.platform.model.Task;
import com.szgz.platform.service.TaskService;
import org.springframework.stereotype.Service;

@Service
public class TaskServiceImpl implements TaskService {

	private final TaskMapper taskMapper;

	public TaskServiceImpl(TaskMapper taskMapper) {
		this.taskMapper = taskMapper;
	}

	@Override
	public Task create(Task task) {
		taskMapper.insert(task);
		return task;
	}

	@Override
	public Task update(Task task) {
		task.setUpdatedAt(java.time.LocalDateTime.now());
		taskMapper.updateById(task);
		// 使用id字段查询，因为现在id是主键
		return taskMapper.selectById(task.getId());
	}

	@Override
	public boolean delete(String taskId) {
		// 先通过taskId查找任务，然后通过id删除
		LambdaQueryWrapper<Task> qw = new LambdaQueryWrapper<>();
		qw.eq(Task::getTaskId, taskId);
		Task task = taskMapper.selectOne(qw);
		if (task != null) {
			return taskMapper.deleteById(task.getId()) > 0;
		}
		return false;
	}

	@Override
	public Task getById(String taskId) {
		// 通过taskId字段查询，保持向后兼容
		LambdaQueryWrapper<Task> qw = new LambdaQueryWrapper<>();
		qw.eq(Task::getTaskId, taskId);
		return taskMapper.selectOne(qw);
	}

	@Override
	public Page<Task> page(long pageNum, long pageSize, String keyword, String status, String type, String difficulty) {
		LambdaQueryWrapper<Task> qw = new LambdaQueryWrapper<>();
		qw.eq(Task::getDeleted, 0);
		if (keyword != null && !keyword.isBlank()) {
			qw.like(Task::getTitle, keyword).or().like(Task::getDescription, keyword);
		}
		if (status != null && !status.isBlank()) qw.eq(Task::getStatus, status);
		if (type != null && !type.isBlank()) qw.eq(Task::getType, type);
		if (difficulty != null && !difficulty.isBlank()) qw.eq(Task::getDifficulty, difficulty);
		qw.orderByDesc(Task::getCreatedAt);
		return taskMapper.selectPage(new Page<>(pageNum, pageSize), qw);
	}
}

